import { createDictData, updateDictData, deleteDictData, listDictDatas } from "@/services/mainten/api";
import type {
  ActionType,
  ProColumns,
} from '@ant-design/pro-components';
import {
  EditableProTable,
  ProFormRadio
} from "@ant-design/pro-components";
import { PageContainer } from "@ant-design/pro-layout";
import { message, Button } from "antd";
import { useNavigate, useParams } from "umi";
import React, { useState, useEffect, useRef } from "react";
import { FormattedMessage,useIntl } from "umi";
import { DictDataVo } from "../constants"




const ListForm: React.FC = () => {
  // const [form] = ProForm.useForm<DictDataVo>();
  const { type } = useParams<{ type: string }>();
  const intl = useIntl();
  const navigate = useNavigate();
  const actionRef = useRef<ActionType>();

  // 当前状态定义
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const [loading, setLoading] = useState(false);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>('bottom');
  const [dataSource, setDataSource] = useState<DictDataVo[]>([]);

  // 建议合并相关状态
  const [tableState, setTableState] = useState({
    loading: false,
    dataSource: [] as DictDataVo[],
    editableKeys: [] as React.Key[],
    position: 'bottom' as 'top' | 'bottom' | 'hidden'
  });


  const columns: ProColumns<DictDataVo>[] = [
    {
      title: (
              <FormattedMessage
                id="pages.dict.data.label"
                defaultMessage="Label Name"
              />
            ),
      dataIndex: 'label',
      valueType: 'text',
      ellipsis: true,
    },
    {
      title: (
              <FormattedMessage
                id="pages.dict.data.sort"
                defaultMessage="Sort Number"
              />
            ),
      dataIndex: 'sort',
      valueType: 'digit',
      ellipsis: true,
    },
    {
      title: (
              <FormattedMessage
                id="pages.dict.data.value"
                defaultMessage="Value"
              />
            ),
      dataIndex: 'value',
      valueType: 'text',
      ellipsis: true,
    },
    {
      title: (
              <FormattedMessage
                id="pages.dict.data.remark"
                defaultMessage="Remark"
              />
            ),
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.operating' }),
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          {intl.formatMessage({ id: 'pages.edit' })}
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await deleteDictData(record.id);
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          {intl.formatMessage({ id: 'pages.delete' })}
        </a>,
      ],
    },
  ];


  const initDictData = async () => {
    const hide = message.loading(intl.formatMessage({ id: 'pages.common.processing' }));
    try {
      // const status = record.customerStatus === 1 ? 0 : 1;
      setLoading(true);
      if (!type) {
        message.error(intl.formatMessage({ id: "request.error.edit" }));
        return false;
      }
      // console.log("type:"+type);
      const response = await listDictDatas(type);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
          return false;
        }
      }
      hide();
      setDataSource(response.data);
      // return response.data;
      return {
        data: response.data,
        total: response.data.length,
        success: true
      };
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: 'request.error.retry' }));
      // return {data: [], total: 0, success: false};
      return [];
    } finally {
      setLoading(false);
    }
  }


  const handleCancel = () => {
    // resetForm();
    navigate(-1);
    // onCancel();
  }

  const handleSave = async (rowKey: React.Key, data: DictDataVo, row: DictDataVo) => {
    // console.log(rowKey);
    // console.log(data);
    // console.log(row);
    try {
      data.dictType = type;
      data.status = 0;
      // data.id = undefined;
      let response;
      if(row.label){
          response =  await updateDictData({ ...data })
      }else{
         data.id = undefined;
         response = await createDictData({ ...data });
      }
      // const response = row.label
      //   ? await updateDictData({ ...data })
      //   : await createDictData({ ...data });

      if (response.code !== 0) {
        throw new Error(response.msg || 'Operator failed');
      }

      message.success(intl.formatMessage({ id: 'pages.operation.success' }));
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: 'request.error.retry' }));
    }
  };


  return (
    <PageContainer extra={[<Button onClick={handleCancel}>
      {/* 返回
    </Button>]}> */}
      {intl.formatMessage({
        id: 'pages.back',
        defaultMessage: 'Return',
      })}</Button>]}>

      <EditableProTable<DictDataVo>
        rowKey="id"
        headerTitle={intl.formatMessage({ id: 'pages.dict.data.list' })}
        // maxLength={5}
        // scroll={{
        //   x: 960,
        // }}
        recordCreatorProps={
          position !== 'hidden'
            ? {
              position: position as 'top',
              record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
            }
            : false
        }
        loading={loading}
        actionRef={actionRef}
        toolBarRender={() => [
          <ProFormRadio.Group
            key="render"
            fieldProps={{
              value: position,
              onChange: (e) => setPosition(e.target.value),
            }}
            options={[
              {
                label: intl.formatMessage({ id: 'pages.position.top' }),
                value: 'top',
              },
              {
                label: intl.formatMessage({ id: 'pages.position.bottom' }),
                value: 'bottom',
              }
            ]}
          />,
        ]}
        columns={columns}
        request={initDictData}
        value={dataSource}
        // onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          onSave: async (rowKey, data, row) => {
            await handleSave(rowKey, data, row);
          },
          onChange: setEditableRowKeys,
        }}
      />

    </PageContainer>
  );
};

export default ListForm;
